package com.swinw.asumall.order.web;

import com.alipay.api.AlipayApiException;
import com.swinw.asumall.order.config.AlipayTemplate;
import com.swinw.asumall.order.entity.OrderEntity;
import com.swinw.asumall.order.service.OrderService;
import com.swinw.asumall.order.vo.PayAsyncVo;
import com.swinw.asumall.order.vo.PayVo;
import com.swinw.common.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

@Controller
public class PayController {

    @Autowired
    AlipayTemplate alipayTemplate;

    @Autowired
    OrderService orderService;


    /**
     * 订单支付成功异步通知
     * @param vo 支付宝沙箱环境返回支付状态信息
     * @return
     */
    @GetMapping("/payNotify")
    public String payNotify(PayAsyncVo vo){
        System.out.println("————————————————————————————————————————" + vo);
        return "";
    }

    /**
     * 1、订单支付成功跳转页面
     * 2、分页查询当前用户的所有订单及订单项信息
     * @return
     */
    @GetMapping("/paySuccess")
    public String paySuccess(@RequestParam Map<String, Object> params, Model model) throws ExecutionException, InterruptedException {
        PageUtils orderEntityList = orderService.getOrderByMemberId(params);
        List<OrderEntity> list = (List<OrderEntity>) orderEntityList.getList();
        model.addAttribute("orders", list);
        return "list";
    }

    /**
     * 订单支付功能
     * @param orderSn
     * @return
     * @throws AlipayApiException
     */
    @ResponseBody
    @GetMapping(value = "/payOrder",produces = "text/html")
    public String payOrder(String orderSn) throws AlipayApiException {

        PayVo vo = orderService.getPayVoByOrderSn(orderSn);
        return alipayTemplate.pay(vo);
    }

}
